/**
 *
 * @author Tomasz Nowak
 */
package TransportLayer;

import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import platform.TenorPlatform;
import sun.awt.image.BytePackedRaster;
import zorg.*;

public class SocketClient implements ISocketClient, IDataTransportable
{
	Socket socket;
	DataOutputStream dataOutputStream;
	DataInputStream dataInputStream;
	ISrtp srtp;

	public SocketClient( String address, int port, ISrtp srtp_ )
	{
		srtp = srtp_;

		try
		{
			socket = new Socket(address, port);
			create();
		}
		catch ( IOException e )
		{
		}
	}

	public SocketClient( InetAddress address, int port, ISrtp srtp_ )
	{
		srtp = srtp_;

		try
		{
			socket = new Socket(address, port);
			create();
		}
		catch ( IOException ex )
		{
			Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE,
																												 null, ex);
		}
	}

	public SocketClient( Socket socket_, ISrtp srtp_ )
	{
		srtp = srtp_;

		try
		{
			socket = socket_;
			create();
		}
		catch ( IOException ex )
		{
			Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE,
																												 null, ex);
		}
	}

	private void create() throws IOException
	{
		dataOutputStream = new DataOutputStream(socket.getOutputStream());
		dataInputStream = new DataInputStream(socket.getInputStream());
	}

	// ISocketClient
	public void sendData( byte[] bytes )
	{
		try
		{
			dataOutputStream.write(bytes);
		}
		catch ( IOException e )
		{
		}
	}

	public void receiveData( byte[] buffer )
	{
//		try
//		{
//			bufferedReader.read(buffer);
//		}
//		catch(IOException e)
//		{
//		}
	}

	public void connect( String computerName )
	{
	}

	public void disconnect()
	{
	}

	// ISocketClient end
	// IDataTransportable
	@Override
	public void sendMessage( byte[] message )
	{
		char[] charMessage = new char[message.length];
		for ( int i = 0; i < message.length; ++i )
		{
			charMessage[i] = ( char ) message[i];
		}

		byte[] srtpPackage = srtp.makePacket(message);

		sendData(srtpPackage);
	}

	@Override
	public InetAddress getRemoteEndpointAddress()
	{
		return socket.getInetAddress();
	}

	@Override
	public int getRemoteEndpointPort()
	{
		return socket.getPort();
	}

	// IDataTransportable end
	@Override
	public byte[] receiveMessage()
	{
		try
		{
			byte[] readingBuffer = new byte[socket.getReceiveBufferSize()];
			System.err.println("receiving");
			dataInputStream.read(readingBuffer);
			/*
			 * here some things connected with receiving only a part of whole message
			 */
			return readingBuffer;
		}
		catch ( SocketException ex )
		{
			Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE,
																												 null, ex);
		}
		catch ( IOException ex )
		{
			Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE,
																												 null, ex);
		}
		return null;
	}
}
